#include <memory.h>
#include <GL/glew.h>

#include "initSDL.h"
#include "log.h"


SDL_Window *InitSDLWindow(const char *title, uint32_t width, uint32_t height) {
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Window *win =
        SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                         width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                        SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
    SDL_GLContext *gl = SDL_GL_CreateContext(win);
    SDL_GL_MakeCurrent(win, gl);
    GLenum err = glewInit();
    if (err != GLEW_OK) {
        const char *msg = (const char *)glewGetErrorString(err);
        puts(msg);
        exit(-1);
    }
    SDL_GL_SetSwapInterval(1);
    LOG_INFO("OpenGL version: %s @render: %s\n", glGetString(GL_VERSION),
           glGetString(GL_RENDERER));
    return win;
}

int InitSDLAudio(int freq, SDL_AudioFormat format, uint8_t channels,
                  uint16_t samples, SDL_AudioCallback callback, void *ud) {
    SDL_AudioSpec spec;
    spec.freq = freq;
    spec.format = format;
    spec.channels = channels;
    spec.silence = 0;
    spec.samples = samples;
    spec.callback = callback;
    spec.userdata = ud;

    if (SDL_OpenAudio(&spec, NULL) < 0) {
        LOG_ERR("SDL can't open audio.\n");
        return -1;
    }
    return 0;
}
